package com.atguigu.tingshu.order.pattern.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.order.pattern.AbstractTradeStrategy;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author NJG
 * @version 1.0
 * @date 2025/8/5 16:10
 * @description
 */
@Slf4j
@Component(SystemConstant.ORDER_ITEM_TYPE_ALBUM)
public class AlbumTrade extends AbstractTradeStrategy {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private AlbumFeignClient albumFeignClient;


    /**
     * 商品类型是专辑
     * @param tradeVo
     * @param userId
     * @return
     */
    @Override
    public OrderInfoVo trade(TradeVo tradeVo, Long userId) {


        log.info("对专辑进行结算");
        //1.创建订单VO对象，创建初始三个金额，两个集合（商品、优惠）
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        //1.1 初始化原价金额 TODO 必须是BigDecimal类型且必须是字符串
        BigDecimal originalAmount = new BigDecimal("0.00");
        //1.2 初始化订单金额
        BigDecimal orderAmount = new BigDecimal("0.00");
        //1.3 初始化减免金额
        BigDecimal derateAmount = new BigDecimal("0.00");

        //1.4. 初始化商品列表集合
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        //1.5. 初始化商品优惠集合
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //1.6 获取购买项目类型 付款项目类型: 1001-专辑 1002-声音 1003-vip会员
        String itemType = tradeVo.getItemType();

        //4.1 处理购买项目类型：专辑
        //远程调用用户服务，判断是否重复购买专辑，如果已购过，则业务终止
        Long albumId = tradeVo.getItemId();
        Boolean flage = userFeignClient.isPaidAlbum(albumId).getData();
        Assert.isFalse(flage, "用户已购买专辑{}！", albumId);

        //4.2 远程调用专辑服务，获取专辑价格以及折扣（普通用户折扣，VIP会员折扣）
        AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
        Assert.notNull(albumInfo, "专辑{}不存在！", albumId);
        BigDecimal price = albumInfo.getPrice();
        BigDecimal discount = albumInfo.getDiscount();
        BigDecimal vipDiscount = albumInfo.getVipDiscount();

        //4.3判断用户是否为VIP会员
        Boolean isVIP = false;
        UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
        if (userInfoVo.getIsVip().intValue() == 1 && userInfoVo.getVipExpireTime().after(new Date())){
            isVIP = true;
        }

        // 计算相关价格
        //暂时将订单价=原价
        originalAmount = price;
        orderAmount = originalAmount;


        //4.4如果是普通用户, 则按照普通用户折扣进行计算
        if (!isVIP && discount.doubleValue() != -1){
            orderAmount = price.multiply(discount)
                    .divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
        }

        //4.5如果是VIP会员, 则按照VIP会员折扣进行计算
        if(isVIP && vipDiscount.doubleValue() != -1){
            orderAmount = price.multiply(vipDiscount)
                    .divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
        }
        //4.6封装商品信息列表
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setItemId(tradeVo.getItemId());
        orderDetailVo.setItemName("专辑："+albumInfo.getAlbumTitle());
        orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
        orderDetailVo.setItemPrice(originalAmount);
        orderDetailVoList.add(orderDetailVo);

        //4.7封装优惠列表
        if (originalAmount.compareTo(orderAmount) == 1){
            derateAmount = originalAmount.subtract(orderAmount);
            OrderDerateVo orderDerateVo = new OrderDerateVo();
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
            orderDerateVo.setDerateAmount(derateAmount);
            orderDerateVo.setRemarks("专辑折扣减免："+derateAmount);
            orderDerateVoList.add(orderDerateVo);
        }



        //5.封装数据
        //5.1三个价格
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        //6.2商品列表&& 订单列表
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);

        //6.封装其他信息：流水号、时间戳及签名、项目类型等
        //6.1封装项目类型
        orderInfoVo.setItemType(itemType);

        //6.2 封装流水号
        generateTradeNo(orderInfoVo, userId);
        //6.3 封装签名
        generateSign(orderInfoVo, userId);
        return orderInfoVo;
    }
}
